﻿using System.Diagnostics;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using ExtendedMvc.Common.Diagnostics;

namespace System {
	public static class StringExtensions {
		[DebuggerStepThrough]
		public static string FormatWith(this string instance, params object[] args) {
			Check.Argument.IsNotNullOrEmpty(instance, "instance");

			return string.Format(CultureInfo.CurrentUICulture, instance, args);
		}

		[DebuggerStepThrough]
		public static string Hash(this string instance) {
			Check.Argument.IsNotNullOrEmpty(instance, "instance");

			using (MD5 md5 = MD5.Create()) {
				byte[] data = Encoding.Unicode.GetBytes(instance);
				byte[] hash = md5.ComputeHash(data);

				return Convert.ToBase64String(hash);
			}
		}

		[DebuggerStepThrough]
		public static T ToEnum<T>(this string instance, T defaultValue) where T : struct, IComparable, IFormattable {
			T convertedValue = defaultValue;

			if (!string.IsNullOrWhiteSpace(instance) && !Enum.TryParse(instance.Trim(), true, out convertedValue)) {
				convertedValue = defaultValue;
			}

			return convertedValue;
		}

		[DebuggerStepThrough]
		public static string ReplaceInvalidChars(this string source, string pattern = "[^a-zA-Z0-9.-:]", string replacement = "_") {
			//Replace charactes not valid for name attribute with underscores.
			return source == null ? null : Regex.Replace(source, pattern, replacement);
		}
	}
}
